package com.tuomaxu.service.impl;

import com.tuomaxu.dao.UserDao;
import com.tuomaxu.pojo.User;
import com.tuomaxu.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean addUser(User user) {
        try {
            User user1  = userDao.save(user);
            System.out.println(user1);
            return true;
        }catch (Exception exception){
            exception.printStackTrace();
            return false;
        }
    }

    @Override
    public User findUserByToken(String token) {
        User user = new User();
        user.setToken(token);
        Example<User> example = Example.of(user);
        User user1 = userDao.findOne(example).get();
        return user1;
    }

    @Override
    public User findUser(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Example<User> example = Example.of(user);
        try {
            User user1 = userDao.findOne(example).get();
            return user1;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public boolean existUser(String email) {
        User user = new User();
        user.setEmail(email);
        Example<User> example = Example.of(user);
        Optional<User> one = userDao.findOne(example);

        try {
            one.get();
            return true;
        }catch (Exception e){
            return false;
        }

    }

    @Override
    public void updateToken(User user) {
        userDao.save(user);
    }
}
